package com.tanhua.mongo.api;

import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 存入用户访问数据
     *
     * @param visitors
     */
    @Override
    public void saveOrUpdate(Visitors visitors) {
        Criteria criteria = Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate());

        if (!mongoTemplate.exists(Query.query(criteria),Visitors.class)){
            mongoTemplate.save(visitors);
        }
    }

    /**
     * 查询当前时间看过我的用户
     *
     * @param data
     * @param userId
     * @return
     */
    @Override
    public List<Visitors> lookVisitors(Long data, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        if (data != null){
            criteria.and("date").gt(data);
        }
        Query query = Query.query(criteria).limit(5).with(Sort.by(Sort.Order.desc("date")));
        return mongoTemplate.find(query,Visitors.class);
    }

}
